// pages/ai/disable/index.js
import Toast from 'tdesign-miniprogram/toast/index';
const {
  ALIOSS
} = require("../../../api/config/config");
import {
  uploadFile
} from "../../../utils/ossUploader";
const {
  aiCreationApi,
  disable,
  globalApi
} = require('../../../api/index')
import {
  DISABLEKEY
} from '../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phoneNumber: '',
    phoneError: false,
    userStatue: '封禁',
    FeedBackDescription: '',
    userStatueCode: 0,
    zhanghao: 2,
    imgList: []
  },

  onLoad(options) {

  },
  onReady() {
    const user= wx.getStorageSync('userInfo')
    globalApi.userbrief({ids:[user.UserId]}).then(e=>{
      this.setData({
        phoneNumber:e.Result[0]?.phoneNumber || ''
      })
    })

    globalApi.getuserstatusasync().then(el => {
      if (el.StatusCode === 200) {
        this.setData({
          userStatueCode: el.Result.UserInfoStatus,
          userStatue: DISABLEKEY[el.Result.UserInfoStatus],
         
        })
      }
    })

  },
  inputChange: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  textareaChange: function (e) {
    this.setData({
      FeedBackDescription: e.detail.value
    })
  },
  onImgDelete(detail) {
    let newArr = this.data.imgList
    const {
      index
    } = detail.currentTarget.dataset;
    newArr.splice(index, 1)
    this.setData({
      imgList: newArr
    })
  },
  generateRandomString() {
    return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  },
  upimages() {
    if (this.data.imgList.length >= 3) return
    let _this = this;
    wx.chooseMedia({
      count: 3,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
      camera: "back",
      success(res) {
        console.log(res);
        _this.setData({
          imgList: [..._this.data.imgList, ...res.tempFiles]
        })
      },
      fail(err) {
        console.error("选择媒体失败", err);
      },
    });
  },
  upLoad(img) {
    let uploadFileName =
      this.generateRandomString() +
      "." +
      img.tempFilePath.split(".")[1];
    return new Promise((resolve, reject) => {
      uploadFile({
          host: `${ALIOSS}`,
          key: `temp/${uploadFileName}`,
          filePath: img.tempFilePath,
        })
        .then((res) => {
          if (res.statusCode == 204) {
            const photoPath = `temp/${uploadFileName}`;
            aiCreationApi
              .ossOperationPicture({
                url: photoPath,
                thumb: {
                  mode: 3,
                  size: {
                    width: 0,
                    height: 1080,
                  },
                },
                format: "",
                targetPath: "image",
              })
              .then((res) => {
                const selectPhotoPath = `${ALIOSS}/${res.url}`; //oss处理后得新地址
                resolve(selectPhotoPath)
              })
              .catch((error) => {
                reject(error)
              });
          }
        })
        .catch((err) => {
          reject(err)
        });
    })

  },
  sunbmit() {
    if (!this.data.phoneNumber || this.data.phoneError) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.data.phoneNumber === '' ? '请输入手机号' : '手机号不正确',
      });
      return
    }
    wx.showLoading({
      title: "请稍等",
    });
    const prList = this.data.imgList.map(e => this.upLoad(e))
    let _this = this
    Promise.all(prList).then(e => {
      disable.createbybanblackasync({
        "FeedBackBanBlack": {
          "PhoneNumber": _this.data.phoneNumber,
          "UserInfoStatus": _this.data.userStatueCode,
          "FeedBackPicList": e,
          "FeedBackDescription": _this.data.FeedBackDescription
        }
      }).then(e => {
        wx.hideLoading();
        const popup = this.selectComponent('#disablePanel');
        _this.setData({
          zhanghao: e.StatusCode === 200 ? 2 : 3
        })
        popup.handlePopup()
      }).catch()

    }).catch(() => {
      wx.hideLoading();
    })
  },
  onPhoneInput(e) {
    const {
      phoneError
    } = this.data;
    const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
    if (phoneError === isPhoneNumber) {
      this.setData({
        phoneError: !isPhoneNumber,
      });
    }
  },
})